package 栈算法;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class preorderTraversal144 {

    /**
     * 二叉树前序遍历
     *
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(Treeroot root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        Deque<Treeroot> stack = new LinkedList<Treeroot>();
        // 判断是否为空或者是的为null
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                // 根 左 右
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }

    public class Treeroot {
        int val;
        Treeroot left;
        Treeroot right;

        Treeroot() {
        }

        Treeroot(int val) {
            this.val = val;
        }

        Treeroot(int val, Treeroot left, Treeroot right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}